//
//  OPHNavgationBar.m
//  OpenPractice
//
//  Created by tanyuehong on 2021/10/20.
//  Copyright © 2021  lijinghua. All rights reserved.
//

#import "OPHomeNavgationBar.h"
#import <Lottie/Lottie.h>
#import "UIColor+Hex.h"
#import "WZLBadgeImport.h"
#import "OPSearchTextView.h"
#import "OPHomeUserLoginBtn.h"
#import "UIButton+TouchArea.h"


@interface OPHomeNavgationBar() <UITextFieldDelegate>

@property (nonatomic, strong) UIView *visualEffectView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, strong) UIView *searchTextView;
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) OPSearchTextView *searchTextLoopView;
@property (nonatomic, strong) NSAttributedString *placeholderString;
@property (nonatomic, strong) OPHomeUserLoginBtn *userBtn;
@property (nonatomic, strong) UIButton *messageBtn;
@property (nonatomic, strong) UILabel *noticeNumLabel;
@property (nonatomic, strong) LOTAnimationView *lottie;
@property (nonatomic, assign) BOOL titleHasHidden;
@property (nonatomic, assign) BOOL willHiddenTitle;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) BOOL badgeShow;
@property (nonatomic, copy) NSArray *loopTexts;
@property (nonatomic, copy) NSString *ABTestValue;

@end

@implementation OPHomeNavgationBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.f];
        self.titleHasHidden = YES;
        self.willHiddenTitle = YES;
    }
    return self;
}

- (void)makeSubviews {
    [self addSubview:self.visualEffectView];
    [self addSubview:self.userBtn];
    [self addSubview:self.titleLabel];
    [self addSubview:self.messageBtn];
    [self addSubview:self.noticeNumLabel];
    [self addSubview:self.lottie];
    [self addSubview:self.lineView];
    [self makeConstraints];
    
    UIView *searchTextView = [[UIView alloc]init];
    searchTextView.layer.cornerRadius = 14.f;
    searchTextView.layer.masksToBounds = YES;
    self.backgroundColor = [UIColor whiteColor];
    searchTextView.backgroundColor = [UIColor colorWithHex:0xf7f9fa];
    UITextField *searchTextField = [[UITextField alloc]init];
    searchTextField.textColor = [UIColor colorWithHex:0x141414];
    searchTextField.backgroundColor = [UIColor clearColor];
    self.placeholderString = [[NSAttributedString alloc]initWithString:@"请输入搜索内容" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithHex:0x626466], NSFontAttributeName:[UIFont systemFontOfSize:12]}];
    searchTextField.attributedPlaceholder = self.placeholderString;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
    UIImage *image = [UIImage imageNamed:@"home_nav_bar_search_icon"];
    UIImageView *biggerView = [[UIImageView alloc] initWithImage:image];
    biggerView.frame = CGRectMake(12, (leftView.frame.size.height - 14) * 0.5, 14, 14);
    biggerView.tintColor = [UIColor colorWithHex:0x626466];
    [leftView addSubview:biggerView];
    searchTextField.leftView = leftView;
    searchTextField.leftViewMode = UITextFieldViewModeAlways;
    searchTextField.layer.cornerRadius = 16;
    searchTextField.delegate = self;
    [self addSubview:searchTextView];
    [searchTextView addSubview:searchTextField];
    self.searchTextView = searchTextView;
    self.searchTextField = searchTextField;
    [self.searchTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.userBtn.mas_right).offset(13);
        make.centerY.equalTo(self.userBtn.mas_centerY);
        make.height.mas_equalTo(28.f);
        make.right.equalTo(self.messageBtn.mas_left).offset(-13);
    }];
    [self resetLoopText];
}

- (void)setBarType:(OPNavgationBarType)barType {
    _barType = barType;
    [self makeSubviews];
}

- (void)makeConstraints {
    [self.visualEffectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self);
    }];
    
    [self.userBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(16);
        make.top.equalTo(self.mas_top).offset(kZDStatusBarHeight+5);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.userBtn.mas_centerY);
    }];
    
    
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.and.height.mas_equalTo(24);
        make.right.equalTo(self.mas_right).offset(-20);
        make.centerY.equalTo(self.userBtn.mas_centerY);
    }];
    
    [self.noticeNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(6);
        make.height.mas_equalTo(6);
        make.left.equalTo(self.messageBtn.mas_right).offset(-6.5);
        make.bottom.equalTo(self.messageBtn.mas_top).offset(6.5);
    }];
    
    [self.lottie mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(28);
        make.height.mas_equalTo(28);
        make.centerY.equalTo(self.userBtn.mas_centerY);
        make.right.equalTo(self.mas_right).offset(-16);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self);
        make.height.mas_equalTo(1.0 / [UIScreen mainScreen].scale);
    }];
}

- (void)resetLoopText {
    @op_weakify(self);
    [TYHHTTPFacade doHttpRequest:nil parms:nil completeBlock:^(NSError *error, NSDictionary *data) {
        if (!error) {
            @op_strongify(self);
            NSArray *texts = [data objectForKey:@"hints"];
            self.loopTexts = texts;
            if (texts.count > 0) {
                [self layoutIfNeeded];
                if (self.searchTextLoopView) {
                    [self.searchTextLoopView resetLoopTexts:texts];
                }else {
                    OPSearchTextView *searchTextLoopView = [[OPSearchTextView alloc] initWithFrame:CGRectMake(32.f, 1.f, CGRectGetWidth(self.searchTextView.frame) - 48.f, CGRectGetHeight(self.searchTextView.frame) - 2.f) texts:texts];
                    [self.searchTextView addSubview:searchTextLoopView];
                    self.searchTextLoopView = searchTextLoopView;
                }
                self.searchTextField.attributedPlaceholder = nil;
            }else {
                if (self.searchTextLoopView) {
                    [self.searchTextLoopView removeFromSuperview];
                    self.searchTextLoopView = nil;
                }
                self.searchTextField.attributedPlaceholder = self.placeholderString;
            }
        }
    }];
}

#pragma mark - Public Method

- (void)setupSearchViewHidden:(BOOL)hidden {
    if (self.searchBtn) {
        self.searchBtn.hidden = hidden;
    }
    if (self.searchTextView) {
        self.searchTextView.hidden = hidden;
    }
}

- (void)updateMsgCount:(NSInteger)msgCount hasNewMsg:(BOOL)hasMsg {
    if (hasMsg) {
        [self.messageBtn showBadge];
    }else if (msgCount > 0) {
        [self.messageBtn showNumberBadgeWithValue:msgCount];
    } else {
        [self.messageBtn clearBadge];
    }
}

- (void)refreshNavgationBar:(CGFloat)persent {
    NSLog(@"滚动persent = %lf", persent);
    BOOL hideTitle = YES;
    if (persent <= 0) {
        hideTitle = NO;
        self.visualEffectView.alpha = 1.f;
    }else {
        hideTitle = YES;
        if ([self.ABTestValue isEqualToString:@"bluetopbar"]) {
            self.visualEffectView.alpha = (1 - persent);
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        }else if ([self.ABTestValue isEqualToString:@"lineartopbar"]) {
            self.visualEffectView.alpha = (1 - persent);
        }
    }
    static BOOL executing = NO;
    self.willHiddenTitle = hideTitle;
    self.lineView.hidden = hideTitle;
   // [self.userBtn refreshBtn:hideTitle];
    // 如果动画正在执行，不重复执行
    if (executing) {
        return;
    }

    // 如果要设置的状态和当前状态的一样，就不重复进行动画了
    if (self.titleHasHidden == hideTitle) {
        return;
    }
    self.titleHasHidden = hideTitle;
    
    executing = YES;
    if ([self.ABTestValue isEqualToString:@"homepagefourbig"] ||
        [self.ABTestValue isEqualToString:@"bluetopbar"] ||
        [self.ABTestValue isEqualToString:@"lineartopbar"]) {
        self.lottie.hidden = YES;
        // 新头部
        if (hideTitle) {
            [UIView animateWithDuration:0.32 delay:0.08 options:UIViewAnimationOptionCurveLinear animations:^{
                self.searchBtn.alpha = 1;
                self.searchTextView.alpha = 1;
                self.messageBtn.alpha = 1;
                self.noticeNumLabel.alpha = 1;
                self.searchTextLoopView.searchTextViewVisable = YES;
            } completion:^(BOOL finished) {
                executing = NO;
                // 检查最后要设置的状态和当前是否一样，不一样按照最后的状态进行更新
                if (self.willHiddenTitle != self.titleHasHidden) {
                    [self refreshNavgationBar:self.willHiddenTitle];
                }
            }];
            
            [UIView animateWithDuration:0.24 delay:0.56 options:UIViewAnimationOptionCurveLinear animations:^{
                self.titleLabel.alpha = 0;
            } completion:nil];
            
        } else {
            [UIView animateWithDuration:0.32 animations:^{
                self.searchBtn.alpha = 0;
                self.searchTextView.alpha = 0;
                self.messageBtn.alpha = 0;
                self.noticeNumLabel.alpha = 0;
                self.searchTextLoopView.searchTextViewVisable = NO;
            }];
            [UIView animateWithDuration:0.2 delay:0.04 options:UIViewAnimationOptionCurveLinear animations:^{
                self.titleLabel.alpha = 1;
            } completion:^(BOOL finished) {
                executing = NO;
                // 检查最后要设置的状态和当前是否一样，不一样按照最后的状态进行更新
                if (self.willHiddenTitle != self.titleHasHidden) {
                    [self refreshNavgationBar:self.willHiddenTitle];
                }
            }];
        }
    }else {
        // 线上头部
        if (hideTitle) {
            @op_weakify(self)
            self.lottie.animationSpeed = -1;
            [self.lottie playWithCompletion:^(BOOL animationFinished) {
                @op_strongify(self)
                self.lottie.alpha = 0;

                [UIView animateWithDuration:0.32 delay:0.08 options:UIViewAnimationOptionCurveLinear animations:^{
                    self.searchBtn.alpha = 1;
                    self.searchTextView.alpha = 1;
                    self.messageBtn.alpha = 1;
                    self.noticeNumLabel.alpha = 1;
                    self.searchTextLoopView.searchTextViewVisable = YES;
                } completion:^(BOOL finished) {
                    executing = NO;
                    // 检查最后要设置的状态和当前是否一样，不一样按照最后的状态进行更新
                    if (self.willHiddenTitle != self.titleHasHidden) {
                        [self refreshNavgationBar:self.willHiddenTitle];
                    }
                }];
            }];
            
            [UIView animateWithDuration:0.24 delay:0.56 options:UIViewAnimationOptionCurveLinear animations:^{
                self.titleLabel.alpha = 0;
            } completion:nil];
            
        } else {
            @op_weakify(self)
            [UIView animateWithDuration:0.32 animations:^{
                self.searchBtn.alpha = 0;
                self.searchTextView.alpha = 0;
                self.messageBtn.alpha = 0;
                self.noticeNumLabel.alpha = 0;
                self.searchTextLoopView.searchTextViewVisable = NO;
            }];
            [UIView animateWithDuration:0.2 delay:0.04 options:UIViewAnimationOptionCurveLinear animations:^{
                self.titleLabel.alpha = 1;
            } completion:^(BOOL finished) {
                self.lottie.alpha = 1;
                self.lottie.animationSpeed = 1;
                [self.lottie playWithCompletion:^(BOOL animationFinished) {
                    @op_strongify(self)
                    executing = NO;
                    // 检查最后要设置的状态和当前是否一样，不一样按照最后的状态进行更新
                    if (self.willHiddenTitle != self.titleHasHidden) {
                        [self refreshNavgationBar:self.willHiddenTitle];
                    }
                }];
            }];
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self clickSearchAction];
    return NO;
}

- (void)showGradeUpdateTipsView:(NSString *)text {
    if (!text || !text.length) {
        return;
    }
//    UXCBubbleTipsView *tips = [[UXCBubbleTipsView alloc]initWithText:text];
//    [tips showTipsFromRect:self.userBtn.frame inView:self direction:UXCBubbleTipsDirectionDown];
//    [tips dismissTipsAnimated:YES atTimeInterval:5];
}

- (void)shouldClean:(BOOL)shouldClean {
    if (shouldClean) {
        
    }else {
        
    }
}

- (void)viewWillAppear {
    if (self.searchTextLoopView) {
        [self.searchTextLoopView resetLoopTexts:self.loopTexts];
    }
}

#pragma mark - Event Action
- (void)clickLeftBtnAction {
    // 未登录时处理红点显示隐藏的逻辑
    if (![TYHLoginManager sharedInstance].isLogin) {
//        [self.userBtn dismissRedDot];
        [self.userBtn clearBadge];
        [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"feedLoginIconRedDotKey"];
    }
    
//    if (self.clickLeftBtnBlcok) {
//        self.clickLeftBtnBlcok();
//    }
}

- (void)clickMessageAction {
    if (self.messageBtn.alpha >= 1.f && self.clickMessageBtnBlock) {
        self.clickMessageBtnBlock();
    }
}

- (void)clickSearchAction {
    if ((self.searchBtn.alpha >= 1.f||self.searchTextView.alpha >= 1.f) && self.clickSearchBtnBlock) {
        if (self.searchBtn) {
            self.clickSearchBtnBlock(nil);
        }else if (self.searchTextView) {
            self.clickSearchBtnBlock(self.searchTextLoopView.curShowText);
        }
    }
}
 
- (void)clickCameraAction {
    if (self.lottie.alpha >= 1.f && self.clickCameraBtnBlock) {
        self.clickCameraBtnBlock();
    }
}

/// 一天间隔策略
- (BOOL)isOverOneDay:(NSString *)key{
    NSTimeInterval currDate = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval lastShowDate = [NSUserDefaults.standardUserDefaults doubleForKey:key];
    if (currDate-lastShowDate<24*60*60) {
        return false;
    }
    return true;
}
- (void)saveShowAlertTimeStamp:(NSString *)key{
    NSTimeInterval currDate = [[NSDate date] timeIntervalSince1970];
    [NSUserDefaults.standardUserDefaults setDouble:currDate forKey:key];
}

#pragma mark - Getter Setter
- (OPHomeUserLoginBtn *)userBtn {
    if (!_userBtn) {
        _userBtn = [[OPHomeUserLoginBtn alloc] init];
        _userBtn.badgeCenterOffset = CGPointMake(24, _userBtn.badgeCenterOffset.y);
        [self userBtnBadgeState:NO];
        // 登录后点击头像的回调处理
        @op_weakify(self)
        _userBtn.clickAvatar = ^{
            @op_strongify(self)
            // 未登录时跳转登录
            if (![TYHLoginManager sharedInstance].isLogin) {
                [self unLoginHeaderImageViewAction];
            } else {
                [self loginHeaderImageViewAction:NO];
            }
            [self.userBtn clearBadge];
        };
    }
    return _userBtn;
}

- (void)userBtnBadgeState:(BOOL)show {
    if ([TYHLoginManager.sharedInstance isLogin]) {
        if (show == YES) {
            if (_badgeShow == NO) {
                [_userBtn showBadge];
            }
        } else [_userBtn clearBadge];
    } else {
        if ([self isOverOneDay:@"HomePageUserBindPhoneAlert"]) {
            if (_badgeShow == NO) {
                [_userBtn showBadge];
            }
        } else [_userBtn clearBadge];
    }
    _badgeShow = show;
}

- (void)unLoginHeaderImageViewAction {
    [self saveShowAlertTimeStamp:@"HomePageUserBindPhoneAlert"];
    [self clickLeftBtnAction];
}

- (void)loginHeaderImageViewAction:(BOOL)show {
    if (show == YES) {
        [self saveShowAlertTimeStamp:@"HomePageUserBindPhoneAlert"];
        [self.userBtn clearBadge];
    }
    if (self.clickAvatarBtnBlock) {
        self.clickAvatarBtnBlock();
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.searchTextField.frame = self.searchTextView.bounds;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.text = @"首页";
        _titleLabel.textColor = [UIColor colorWithHex:0x141414];
        _titleLabel.font = [UIFont systemFontOfSize:18.0];
        _titleLabel.alpha = 0;
    }
    return _titleLabel;
}


- (UIButton *)messageBtn {
    if (!_messageBtn) {
        _messageBtn = [UIButton new];
        if (self.barType == OPNavgationBarTypeHome) {
            [_messageBtn setImage:[UIImage imageNamed:@"home_nav_xiaoxi"] forState:UIControlStateNormal];
        } else {
            [_messageBtn setImage:[UIImage imageNamed:@"pratice_user_faver"] forState:UIControlStateNormal];
        }
        [_messageBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];
        [_messageBtn addTarget:self action:@selector(clickMessageAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageBtn;
}

- (UILabel *)noticeNumLabel {
    if (!_noticeNumLabel) {
        _noticeNumLabel = [UILabel new];
        _noticeNumLabel.backgroundColor = [UIColor colorWithHex:0xF54327];
        _noticeNumLabel.textColor = [UIColor whiteColor];
        _noticeNumLabel.textAlignment = NSTextAlignmentCenter;
        _noticeNumLabel.font = [UIFont systemFontOfSize:9.0];
        _noticeNumLabel.layer.cornerRadius = 3;
        _noticeNumLabel.layer.masksToBounds = YES;
        _noticeNumLabel.hidden = YES;
    }
    return _noticeNumLabel;
}

- (LOTAnimationView *)lottie {
    if (!_lottie) {
        _lottie = [LOTAnimationView animationNamed:@"HomeCameraIconAnimation"];
        _lottie.autoReverseAnimation = NO;
        _lottie.loopAnimation = NO;
        _lottie.alpha = 0;
       // [_lottie addTapGestureWithTarget:self selector:@selector(clickCameraAction)];
    }
    return _lottie;
}

- (UIView *)visualEffectView {
    if (!_visualEffectView) {
        _visualEffectView = [[UIView alloc]init];
        _visualEffectView.backgroundColor = [UIColor whiteColor];
//        [_visualEffectView setLayerShadow:[UIColor colorWithHex:0x141414 andAlpha:0.04] offset:CGSizeMake(0, 2) radius:8];
    }
    return _visualEffectView;
}

- (UIView *)lineView {
    if (_lineView == nil) {
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = [UIColor colorWithHex:0xedeff0];
        _lineView.hidden = YES;
    }
    return _lineView;
}

@end
